﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fcom.VNInsurance.Web.CultureHelper;
using System.Web.Security;
namespace Fcom.VNInsurance.Web.Controllers
{
    public class MotoController : CultureController
    {
        //
        // GET: /Moto/
        VNInsurance.Web.Models.VNInsuranceDataContext db = new Models.VNInsuranceDataContext();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Motopayment()
        {
            if (Session["motopolicyid"] == null)
                return RedirectToAction("Motobike");
            var news = db.NewsLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.New.NCatID == 8);
            return View(news);
        }
        public ActionResult Motobike()
        {
            string langid = Request.Cookies["_culture"]["lang"];
 
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 12 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;
            var autocategory = db.AutoCategories.Where(a=>a.Motobikes.Count()>0);
            ViewBag.autoSelectList = new SelectList(autocategory, "ID", "Name", 1);            
            var motobikes = db.Motobikes.Where(m=>m.AutoCatID==1);//
            ViewBag.bikeSelectList = new SelectList(motobikes, "ID", "Name");
          
            var coveragebase = (from cv in db.CoverageBaseProducts where cv.ProductID==12 select cv).FirstOrDefault();

            ViewBag.bhtnds = db.BenefitLangs.Where(m => m.BenefitID == 1 && m.LangID == langid).FirstOrDefault();
            ViewBag.bhtainan = db.BenefitLangs.Where(m => m.BenefitID == 3 && m.LangID == langid).FirstOrDefault();
            ViewBag.bhvcxemay = db.BenefitLangs.Where(m => m.BenefitID == 4 && m.LangID == langid).FirstOrDefault();
            ViewBag.bhtonthat = db.BenefitLangs.Where(m => m.BenefitID == 5 && m.LangID == langid).FirstOrDefault();      
            

            /*
            Fcom.VNInsurance.Web.Models.BaseBenefitLang bl; //benefitlang base 
            List<Fcom.VNInsurance.Web.Models.BaseBenefitLang> ListBenefit = new List<Models.BaseBenefitLang>();
            foreach (var bb in baseBenefits)
            {
                var LBBenefit = db.BenefitLangs.Where(m => m.BenefitID == bb.BenefitID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
                if (LBBenefit != null)
                {
                    bl = new Models.BaseBenefitLang();
                    bl.BenefitID = LBBenefit.BenefitID;
                    bl.Detail = LBBenefit.Detail;
                    bl.Displayname = LBBenefit.DisplayName;
                    bl.EnableInsMoney = LBBenefit.EnableInsMoney;
                    bl.EnableSubMoney = LBBenefit.EnableSub;
                    bl.InputKey = LBBenefit.Benefit.InputKey;
                    ListBenefit.Add(bl);
                }
            }
            ViewBag.baseBenefitLst = ListBenefit;
             */
            var insurancemoneys = db.MotobikeInsMoneys.OrderBy(m=>m.InsuanceMoney);
            List<SelectListItem> ListNumber = new List<SelectListItem>();
            foreach (var ins in insurancemoneys)
            {
                ListNumber.Add(new SelectListItem() { Text = @String.Format("{0:#,###,###}", ins.InsuanceMoney), Value = ins.InsuanceMoney.ToString() });
            }
            

            ViewBag.InsMoneys = ListNumber;
            var subsmoney = db.MotobikeSubmoneys.OrderBy(m=>m.MotoSubmoney);
          
            List<SelectListItem> ListSubmoney = new List<SelectListItem>();
            foreach (var subs in subsmoney)
            {
                ListSubmoney.Add(new SelectListItem() { Text = @String.Format("{0:#,###,###}", subs.MotoSubmoney), Value = subs.MotoSubmoney.ToString() });
            }
       
            ViewBag.Submoney = ListSubmoney;
            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 12);

            return View(LangProduct);
        }
        private bool searchElement(string[] values, string key)
        {
            bool search = false;
            foreach (var va in values)
            {
                if (key == va)
                {
                    search = true;
                    break;
                }
            }
            return search;
        }
        private Models.CusChoose searchsuschoose(List<Models.CusChoose> list,int benefitid)
        {
            Models.CusChoose cus = null;
            foreach (var c in list)
            {
                if (c.BenefitID == benefitid)
                {
                    cus = c;
                    break;
                }
            }
            return cus;
        }
        [HttpPost]
        public ActionResult Motobike(FormCollection formdata)
        {
            bool isauth = bool.Parse(formdata["isAuth"]);
            var coveragebase = (from cv in db.CoverageBaseProducts where cv.ProductID == 12 select cv).FirstOrDefault();
            var benefits = db.Benefits.Where(m=>m.CoverageID==coveragebase.CoverageID&&m.ParentID==null);
            List<Models.CusChoose> listchoose = new List<Models.CusChoose>();
            Models.CusChoose cuschoose;
            string[] allkey = formdata.AllKeys;
            foreach (var be in benefits)
            {
                    
                    cuschoose = new Models.CusChoose();
                    cuschoose.BenefitID = int.Parse(formdata["befitid" + be.InputKey]);
                    cuschoose.isChoose =  bool.Parse(formdata["rd" + be.InputKey]);
                    if (cuschoose.isChoose)
                    {
                        string insmm = formdata[be.InputKey + "InsMoney"];
                        if (searchElement(allkey, be.InputKey + "InsMoney"))
                        {
                            cuschoose.InsuranceMoney = int.Parse(insmm.Replace(".", "").Replace(",", ""));
                        }
                        if (searchElement(allkey, be.InputKey + "SubMoney"))
                        {
                            cuschoose.SubMoney = int.Parse(formdata[be.InputKey + "SubMoney"]);
                        }
                        listchoose.Add(cuschoose);
                    }
            }
            Session["moto_collect"] = listchoose;
            Models.MotoCatelogChoose motocatelogchoose = new Models.MotoCatelogChoose();
            motocatelogchoose.AutoID = int.Parse(formdata["Manufacturer"]);
            motocatelogchoose.ModelID = int.Parse(formdata["Model"]);
            motocatelogchoose.Year = int.Parse(formdata["Year"]);
            motocatelogchoose.MotoPrice = long.Parse(formdata["giatrixe"].Replace(".","").Replace(",",""));

            var moto = db.Motobikes.Where(m => m.ID == motocatelogchoose.ModelID).FirstOrDefault();
            motocatelogchoose.CC = moto.CC;
            Session["moto_collect_motobike"] = motocatelogchoose;

            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 12 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            if (!isauth)
            {
                bool haveaccount = bool.Parse(formdata["haveAccount"]);
                if (haveaccount)
                {
                    return RedirectToAction("MotobikeCompare");
                }
                else
                {
                    int accounttype = int.Parse(formdata["accountype"]);
                    if (accounttype == 1)
                    {
                        bool gender = bool.Parse(formdata["gender"]);
                        string username = formdata["youremail"];
                        string phone = formdata["yourphone"];
                        string fullname = formdata["yourfullname"];
                        DateTime dateofbirth;
                        try
                        {
                            dateofbirth = DateTime.Parse(formdata["dateofBirth"]);
                        }
                        catch
                        {
                            dateofbirth = DateTime.Now;
                        }

                        Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
                        if (client.CreateAccountFl(username, phone, fullname, gender, accounttype, dateofbirth))
                        {
                            FormsAuthentication.SetAuthCookie(username, true);
                            return RedirectToAction("MotobikeCompare");
                        }
                        client.Close();

                    }
                    else
                    {

                        string username = formdata["youremail"];
                        string phone = formdata["yourphone"];
                        string fullname = formdata["yourfullname"];
                        Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
                        if (client.CreateAccountFl(username, phone, fullname, true, accounttype, DateTime.Now))
                        {
                            FormsAuthentication.SetAuthCookie(username, true);
                            return RedirectToAction("MotobikeCompare");
                        }
                        client.Close();
                    }
                }
            }
            else
            {
                
                return RedirectToAction("MotobikeCompare");
            }
            ViewBag.LangCat = LangCatProduct;

            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 4);

            return View(LangProduct);
           
        }
      
        [Authorize]
        public ActionResult MotobikeCompare()
        {
            if (Session["moto_collect"] == null || Session["moto_collect_motobike"]==null)
            {
                return RedirectToAction("Motobike");
            }
            List<Models.CusChoose> listcuschoose = (List<Models.CusChoose>)Session["moto_collect"];
            string listben = "";
            int numberbe = 0;
            foreach (var lis in listcuschoose)
            {
                if (lis.isChoose)
                {
                    numberbe += 1;
                    listben += lis.BenefitID + ",";
                }
            }
            Models.MotoCatelogChoose MotoChoose = (Models.MotoCatelogChoose)Session["moto_collect_motobike"];

          

            bool showgara = false;
            bool showhopital = false;
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 12 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = LangProduct;
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            if (LangCatProduct.CatID == 2)
            { showhopital = true; }
            if (LangCatProduct.CatID == 3)
            { showgara = true; }

            ViewBag.LangCat = LangCatProduct;
            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 12);

            var LangCPProduct =( from cp in db.CompanyProductLangs
                                where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CompanyProduct.ProductID == 12 && cp.CompanyProduct.Enable == true && cp.CompanyProduct.Company.Enable == true && cp.CompanyProduct.CompanyProductBenefits.Where(a => a.LangID == Request.Cookies["_culture"]["lang"]).Count() >= numberbe
                                 orderby cp.CompanyProduct.CompanyProductBenefits.Where(a => a.LangID == Request.Cookies["_culture"]["lang"]).Count()
                                select new Fcom.VNInsurance.Web.Models.CPInfo()
                                { showGaras = showgara, showHopitals = showhopital, Condition = cp.Condition, ProductImage = cp.ProductImage, CompanyID = cp.CompanyProduct.CompanyID, CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney }).ToList();
            ViewBag.CurrentLang = LangProduct.Language;
            long insuancemoney,fare;
            List<Models.CPInfo> listremove = new List<Models.CPInfo>();
            foreach (var cpp in LangCPProduct)
            {
                insuancemoney = 0;
                fare = 0;
                var benefits = db.CompanyProductBenefits.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]&&n.CProductId==cpp.CProductID).OrderBy(m=>m.BenefitID).ToList();

                string bennss = "";
                    foreach (var benn in benefits)
                    {
                        bennss += benn.BenefitID + ",";
                        if (benn.MotobikeCCFare)
                        {
                            if (MotoChoose.CC > 50)
                            {
                                fare += benn.MotoUpInsuranceFare;
                            }
                            else
                            {
                                fare += benn.MotoDownInsuranceFare;
                            }
                           // insuancemoney += benn.InsuanceMoney;
                        }
                         else if (benn.RateBenefit)
                           {
                        
                              fare +=Convert.ToInt64(Math.Round(MotoChoose.MotoPrice* benn.Rate,0));
                              //insuancemoney += MotoChoose.MotoPrice;
                           }
                        else
                        {
                            //insuancemoney += benn.InsuanceMoney;
                            fare += benn.InsuanceFare;
                        }

                        if (benn.InsmoneyByPrice)
                        {
                            insuancemoney += MotoChoose.MotoPrice;
                        }
                        else
                        {
                            insuancemoney += benn.InsuanceMoney;
                        }
                    }
                cpp.Fare = fare;
                cpp.InsuranceMoney = insuancemoney;
                if (!bennss.Contains(listben))
                {
                    listremove.Add(cpp);
                }
                
            }
            foreach (var removeitem in listremove)
            {
                LangCPProduct.Remove(removeitem);
            }
            return View(LangCPProduct);
        }
        [HttpPost]
        public ActionResult cpMotoGarasJson(int ID)
        { 
          var coveragecp = db.CoverageBaseCompanyProducts.Where(m=>m.CProductID==ID).FirstOrDefault();
          var garas = from m in db.GaraLangs where m.Gara.CoverageBaseGaras.FirstOrDefault().CoverageID == coveragecp.CoverageID where m.LangID == Request.Cookies["_culture"]["lang"] select new { m.GaraID, m.GaraName, m.Address, m.Phone, m.Fax };
            return Json(garas, JsonRequestBehavior.AllowGet);
        }
        public ActionResult motobikedetail(int ID)
        {
            if (Session["moto_collect"] == null || Session["moto_collect_motobike"] == null)
            {
                return RedirectToAction("Motobike");
            }

            Models.MotoCatelogChoose MotoChoose = (Models.MotoCatelogChoose)Session["moto_collect_motobike"];
            var companyproductlang = db.CompanyProductLangs.Where(m => m.CProductID == ID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == companyproductlang.CompanyProduct.ProductID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = LangProduct;
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;
            bool showgara = false;
            bool showhopital = false;

            if (LangCatProduct.CatID == 2)
            { showhopital = true; }
            if (LangCatProduct.CatID == 3)
            { showgara = true; }
            var LangCPProduct = (from cp in db.CompanyProductLangs
                                 where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CProductID == ID && cp.CompanyProduct.Enable == true && cp.CompanyProduct.Company.Enable == true
                                 select new Fcom.VNInsurance.Web.Models.CPInfo() { showGaras = showgara, showHopitals = showhopital, Condition = cp.Condition, ProductImage = cp.ProductImage, CompanyID = cp.CompanyProduct.CompanyID, Intro = cp.Intro, CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney }).FirstOrDefault();

            long insuancemoney, fare;
            
                insuancemoney = 0;
                fare = 0;
                var benefits = db.CompanyProductBenefits.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.CProductId == LangCPProduct.CProductID).ToList();
                foreach (var benn in benefits)
                {

                    if (benn.MotobikeCCFare)
                    {
                        if (MotoChoose.CC > 50)
                        {
                            fare += benn.MotoUpInsuranceFare;
                        }
                        else
                        {
                            fare += benn.MotoDownInsuranceFare;
                        }
                        // insuancemoney += benn.InsuanceMoney;
                    }
                    else if (benn.RateBenefit)
                    {

                        fare += Convert.ToInt64(Math.Round(MotoChoose.MotoPrice * benn.Rate, 0));
                        //insuancemoney += MotoChoose.MotoPrice;
                    }
                    else
                    {
                        //insuancemoney += benn.InsuanceMoney;
                        fare += benn.InsuanceFare;
                    }
                    if (benn.InsmoneyByPrice)
                    {
                        insuancemoney += MotoChoose.MotoPrice;
                    }
                    else
                    {
                        insuancemoney += benn.InsuanceMoney;
                    }
                }
                LangCPProduct.Fare = fare;
                LangCPProduct.InsuranceMoney = insuancemoney;
            if (LangCPProduct == null)
            {
                return RedirectToAction(LangProduct.Product.Action, LangProduct.Product.Controller);
            }
         

            var OtherLangCPProduct = from cp in db.CompanyProductLangs
                                     where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CProductID != ID && cp.CompanyProduct.CompanyID == companyproductlang.CompanyProduct.CompanyID && cp.CompanyProduct.ProductID == LangProduct.ProductID && cp.CompanyProduct.Enable == true && cp.CompanyProduct.Company.Enable == true
                                     select new Fcom.VNInsurance.Web.Models.CPInfo() { showGaras = showgara, showHopitals = showhopital, Condition = cp.Condition, ProductImage = cp.ProductImage, CompanyID = cp.CompanyProduct.CompanyID, Intro = cp.Intro, CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney };

            ViewBag.CurrentLang = LangProduct.Language;
            ViewBag.OtherLangCPProduct = OtherLangCPProduct;
            return View(LangCPProduct);
        }
        [Authorize]
        public ActionResult MotobikeApply(int ID)
        {
            if (Session["moto_collect"] == null || Session["moto_collect_motobike"] == null)
            {
                return RedirectToAction("Motobike");
            }
            Models.MotoCatelogChoose MotoChoose = (Models.MotoCatelogChoose)Session["moto_collect_motobike"];

            bool showgara = false;
            bool showhopital = false;
            Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
            Fcom.IDLib.SaveMoneyID.FullUserInfo fullinfo = client.getUserInfo(User.Identity.Name);
            client.Close();
            ViewBag.Userinfo = fullinfo;
            var LangCPProduct = (from cp in db.CompanyProductLangs
                                 where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CProductID == ID && cp.CompanyProduct.Enable == true && cp.CompanyProduct.Company.Enable == true
                                 select new Fcom.VNInsurance.Web.Models.CPInfo() { showGaras = showgara, showHopitals = showhopital, Condition = cp.Condition, ProductImage = cp.ProductImage, CompanyID = cp.CompanyProduct.CompanyID, Intro = cp.Intro, CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney }).FirstOrDefault();
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 12 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;

            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 12);
            var benefits = from n in db.CompanyProductBenefits where n.LangID == Request.Cookies["_culture"]["lang"] && n.CProductId == LangCPProduct.CProductID select new Models.BenefitFare() { BenefitID = n.BenefitID, BenefitName = n.Benefit.BenefitLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().DisplayName,Fare=n.InsuanceFare,MotoDown=n.MotoDownInsuranceFare,MotoUp=n.MotoUpInsuranceFare,isMotoCC=n.MotobikeCCFare,Rate=n.Rate,RateBenefit=n.RateBenefit,InsMoney=n.InsuanceMoney,InsbyMoto=n.InsmoneyByPrice};
            ViewBag.benefits = benefits;
            ViewBag.MotoChoose = MotoChoose;

            ViewBag.motopaper = db.CompanyProductPapers.Where(m => m.CProductID == ID);

            return View(LangCPProduct);
        }
        [HttpPost]
        public ActionResult cpMotoDocsJson(int ID)
        { 
            var docs= from m in db.CompanyProductDocs where m.CProductID==ID select new {m.ID,m.istype,m.Value,m.Title};
            return Json(docs, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult MotobikeApply(FormCollection form)
        {
            if (Session["moto_collect"] == null || Session["moto_collect_motobike"] == null)
            {
                return RedirectToAction("Motobike");
            }
            Models.MotoCatelogChoose MotoChoose = (Models.MotoCatelogChoose)Session["moto_collect_motobike"];

            Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
            Fcom.IDLib.SaveMoneyID.FullUserInfo fullinfo = client.getUserInfo(User.Identity.Name);
            client.Close();

            string owner = form["txt_owner"];
            string txt_address_register = form["txt_address_register"];
            string txt_bikeid = form["txt_bikeid"];
            string txt_machineid = form["txt_machineid"];
            string txt_frameid = form["txt_frameid"];
            int hour = int.Parse(form["hour"]);
            string txt_date = form["txt_date"];
            string txt_name = form["txt_name"];
            string txt_email = form["txt_email"];
            string txt_phone = form["txt_phone"];
            string txt_address = form["txt_address"];
           
            int cpid = int.Parse(form["CProductID"]);

            long insuancemoney, fare;

            insuancemoney = 0;
            fare = 0;
            var benefits = db.CompanyProductBenefits.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.CProductId == cpid).ToList();
            foreach (var benn in benefits)
            {

                if (benn.MotobikeCCFare)
                        {
                            if (MotoChoose.CC > 50)
                            {
                                fare += benn.MotoUpInsuranceFare;
                            }
                            else
                            {
                                fare += benn.MotoDownInsuranceFare;
                            }
                           // insuancemoney += benn.InsuanceMoney;
                        }
                     else if (benn.RateBenefit)
                       {
                        
                          fare +=Convert.ToInt64(Math.Round(MotoChoose.MotoPrice* benn.Rate,0));
                          //insuancemoney += MotoChoose.MotoPrice;
                       }
                        else
                        {
                            //insuancemoney += benn.InsuanceMoney;
                            fare += benn.InsuanceFare;
                        }
                        if (benn.InsmoneyByPrice)
                        {
                            insuancemoney += MotoChoose.MotoPrice;
                        }
                        else
                        {
                            insuancemoney += benn.InsuanceMoney;
                        }
            }
           

            Models.Policy policy = new Models.Policy();
            policy.Address = txt_address_register;
         
            policy.CProductID = cpid;
            policy.Email = fullinfo.Email;
            policy.Fax = fullinfo.Fax;
            policy.FullName = fullinfo.Fullname;
            policy.Gender = fullinfo.Gender;
            policy.IdentityOrTaxCode = fullinfo.IDentityCode;
            policy.Phone = fullinfo.Phone;
            policy.PolicyDate = DateTime.Now;
            policy.TotalFare = fare;//tongphi
            policy.username = fullinfo.Username;

            db.Policies.InsertOnSubmit(policy);
            db.SubmitChanges();
            Models.PolicyMotobiker pmoto = new Models.PolicyMotobiker();
            pmoto.Address = txt_address_register;
            pmoto.ItemIdentityCode = txt_bikeid;
            pmoto.MachineCode = txt_machineid;
            pmoto.MotobikeID = MotoChoose.ModelID;
            pmoto.OwnerFullname = owner;
            pmoto.PolicyID = policy.PolicyID;
            pmoto.MotoPrice = MotoChoose.MotoPrice;
            pmoto.BeginDate = DateTime.ParseExact(txt_date, "dd/MM/yyyy", null);
            db.PolicyMotobikers.InsertOnSubmit(pmoto);

            Models.PolicyShipping ship = new Models.PolicyShipping();
            ship.Address = txt_address;
            ship.Email = txt_email;
            ship.FullName = txt_name;
            ship.Phone = txt_phone;
            ship.PolicyID = policy.PolicyID;
            db.PolicyShippings.InsertOnSubmit(ship);
            db.SubmitChanges();
            Session["motopolicyid"] = policy.PolicyID;
            return RedirectToAction("Motopayment");
        }
        [Authorize]
        public ActionResult MotoFinal(int ID)
        {
            
            var policy = db.Policies.Where(m=>m.PolicyID==ID&&m.username==User.Identity.Name).FirstOrDefault();
            if (policy == null)
            {
                return RedirectToAction("Motobike");
            }
            
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 12 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCPProduct = (from cp in db.CompanyProductLangs
                                 where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CProductID == policy.CProductID && cp.CompanyProduct.Enable == true && cp.CompanyProduct.Company.Enable == true
                                 select new Fcom.VNInsurance.Web.Models.CPInfo() { Condition = cp.Condition, ProductImage = cp.ProductImage, CompanyID = cp.CompanyProduct.CompanyID, Intro = cp.Intro, CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney }).FirstOrDefault();

            ViewBag.LangCat = LangCatProduct;
            ViewBag.policy = policy;
            
            var policymoto = db.PolicyMotobikers.Where(m => m.PolicyID == policy.PolicyID).FirstOrDefault();
            ViewBag.policymotobiker=policymoto;
            ViewBag.policyshiping = db.PolicyShippings.Where(m=>m.PolicyID==policy.PolicyID).FirstOrDefault();
            Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
            Fcom.IDLib.SaveMoneyID.FullUserInfo fullinfo = client.getUserInfo(User.Identity.Name);
            client.Close();
            ViewBag.Userinfo = fullinfo;
            ViewBag.motobike = db.Motobikes.Where(m => m.ID == policymoto.MotobikeID).FirstOrDefault() ;
            var benefits = from n in db.CompanyProductBenefits where n.LangID == Request.Cookies["_culture"]["lang"] && n.CProductId == LangCPProduct.CProductID select new Models.BenefitFare() { BenefitID = n.BenefitID, BenefitName = n.Benefit.BenefitLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().DisplayName, Fare = n.InsuanceFare, MotoDown = n.MotoDownInsuranceFare, MotoUp = n.MotoUpInsuranceFare, isMotoCC = n.MotobikeCCFare };
            ViewBag.benefits = benefits;

            return View(LangCPProduct);
        }
        private bool searchbenefit(List<Models.CompanyProductBenefit> list, int benefitid)
        {
            bool re = false;
            foreach (var li in list)
            {
                if (benefitid == li.BenefitID)
                {
                    re = true;
                    break;
                }
            }
            return re;
        }
        public ActionResult RepareInfo()
        {
           return View();
        }
        [HttpPost]
        public ActionResult ajLoadMotobike(int CatID)
        {
            var motobikes = from m in db.Motobikes where m.AutoCatID == CatID select new { m.ID,m.Name};
            return Json(motobikes);
        }

        [HttpPost]
        public ActionResult ajLoadCar(int CatID)
        {
            var motobikes = from m in db.Cars where m.AutoCatID == CatID select new { m.ID, m.Name,m.Year,m.SeatNumber,m.Image };
            return Json(motobikes);
        }
        public ActionResult Car()
        {
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 11 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;
            var autocategory = db.AutoCategories.Where(a => a.Cars.Count() > 0);
            var firstauto = autocategory.FirstOrDefault();
            ViewBag.autoSelectList = new SelectList(autocategory, "ID", "Name",firstauto.ID);
            var cars = db.Cars.Where(m => m.AutoCatID == firstauto.ID);//
            ViewBag.bikeSelectList = cars;
            ViewBag.firstcar = cars.FirstOrDefault();
           

            var economic= db.MotoEconomicLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]);

            ViewBag.economictype = new SelectList(economic, "MotoEID", "Displayname");
            //
            var coveragebase = (from cv in db.CoverageBaseProducts where cv.ProductID == 11 select cv).FirstOrDefault();
            var bebefit = from ben in db.BenefitLangs where ben.Benefit.CoverageID == coveragebase.CoverageID && Request.Cookies["_culture"]["lang"] == ben.LangID&&ben.Benefit.ParentID==null select ben;
            
            ViewBag.baseBenefitLst = bebefit;
            Dictionary<int, List<Fcom.VNInsurance.Web.Models.BenefitLang>> childbenefit = new Dictionary<int, List<Models.BenefitLang>>();
            foreach (var bee in bebefit)
            {
                if (bee.EnableChildBenefit)
                {
                    var benefitchild = db.BenefitLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.Benefit.ParentID == bee.BenefitID).ToList();
                    childbenefit.Add(bee.BenefitID, benefitchild);
                }
            }
            ViewBag.childbenefits = childbenefit;


            List<SelectListItem> ListNumber = new List<SelectListItem>();
            for (int i = 10; i <= 100; i += 10)
            {
                ListNumber.Add(new SelectListItem() { Text = i.ToString() +" "+ Fcom.VNInsurance.Web.LangResource.ContactLayout.lblMilionVND, Value = i.ToString() });
            }
            ViewBag.InsMoneys = ListNumber;

            List<SelectListItem> ListSubmoney = new List<SelectListItem>();
            for (int i = 1000000; i <= 10000000; i += 1000000)
            {
                ListSubmoney.Add(new SelectListItem() { Text = @String.Format("{0:#,###,###}", i), Value = i.ToString() });
            }
            ViewBag.Submoney = ListSubmoney;
            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 11);

            return View(LangProduct);
        }
        [HttpPost]
        public ActionResult Car(FormCollection formdata)
        {
            bool isauth = bool.Parse(formdata["isAuth"]);
            var LangProduct = db.ProductLangs.Where(p => p.ProductID == 11 && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            if (!isauth)
            {
                bool haveaccount = bool.Parse(formdata["haveAccount"]);
                if (haveaccount)
                {
                    return RedirectToAction("Compare", "CompanyProduct", new { ID = LangProduct.ProductID, CatName = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangCatProduct.DisplayName), Name = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangProduct.DisplayName) });
                }
                else
                {
                    int accounttype = int.Parse(formdata["accountype"]);
                    if (accounttype == 1)
                    {
                        bool gender = bool.Parse(formdata["gender"]);
                        string username = formdata["youremail"];
                        string phone = formdata["yourphone"];
                        string fullname = formdata["yourfullname"];
                        DateTime dateofbirth;
                        try
                        {
                            dateofbirth = DateTime.Parse(formdata["dateofBirth"]);
                        }
                        catch
                        {
                            dateofbirth = DateTime.Now;
                        }

                        Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
                        if (client.CreateAccountFl(username, phone, fullname, gender, accounttype, dateofbirth))
                        {
                            FormsAuthentication.SetAuthCookie(username, true);
                            return RedirectToAction("Compare", "CompanyProduct", new { ID = LangProduct.ProductID, CatName = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangCatProduct.DisplayName), Name = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangProduct.DisplayName) });
                        }
                        client.Close();

                    }
                    else
                    {

                        string username = formdata["youremail"];
                        string phone = formdata["yourphone"];
                        string fullname = formdata["yourfullname"];
                        Fcom.IDLib.SaveMoneyID.AccountsynClient client = new IDLib.SaveMoneyID.AccountsynClient();
                        if (client.CreateAccountFl(username, phone, fullname, true, accounttype, DateTime.Now))
                        {
                            FormsAuthentication.SetAuthCookie(username, true);
                            return RedirectToAction("Compare", "CompanyProduct", new { ID = LangProduct.ProductID, CatName = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangCatProduct.DisplayName), Name = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangProduct.DisplayName) });
                        }
                        client.Close();
                    }
                }
            }
            else
            {
                return RedirectToAction("Compare", "CompanyProduct", new { ID = LangProduct.ProductID, CatName = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangCatProduct.DisplayName), Name = Fcom.VNInsurance.Web.Utils.Url.url_rewrite(LangProduct.DisplayName) });
            }
            ViewBag.LangCat = LangCatProduct;

            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == 4);

            return View(LangProduct);

        }

    }
}
